import { defineStore } from 'pinia'
import { ref, computed, nextTick } from 'vue'
import { login, logout, getUserInfo, getProfile, updateProfile, uploadAvatar } from '@/api/auth'
import { setToken, getToken, removeToken } from '@/utils/auth'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(getToken() || '')
  const userInfo = ref({})
  const roles = ref([])
  const permissions = ref([])

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const hasRole = computed(() => (role) => roles.value.includes(role))
  const hasPermission = computed(() => (permission) => permissions.value.includes(permission))

  // 登录
  const loginAction = async (loginForm) => {
    try {
      const response = await login(loginForm)
      const { token: userToken, user } = response.data
      
      token.value = userToken
      userInfo.value = user
      setToken(userToken)
      
      return response
    } catch (error) {
      throw error
    }
  }

  // 登出
  const logoutAction = async () => {
    try {
      await logout()
    } catch (error) {
      console.error('登出失败:', error)
    } finally {
      resetUserInfo()
    }
  }

  // 获取用户信息
  const getUserInfoAction = async () => {
    try {
      const response = await getUserInfo()
      const { user, roles: userRoles, permissions: userPermissions } = response.data
      
      userInfo.value = user
      roles.value = userRoles || []
      permissions.value = userPermissions || []
      
      return response
    } catch (error) {
      throw error
    }
  }

  // 初始化用户信息
  const initUserInfo = async () => {
    if (token.value) {
      try {
        await getUserInfoAction()
      } catch (error) {
        console.error('获取用户信息失败:', error)
        resetUserInfo()
      }
    }
  }

  // 重置用户信息
  const resetUserInfo = () => {
    token.value = ''
    userInfo.value = {}
    roles.value = []
    permissions.value = []
    removeToken()
  }

  // 获取个人资料
  const getProfileAction = async () => {
    try {
      const response = await getProfile()
      return response
    } catch (error) {
      throw error
    }
  }

  // 更新个人资料
  const updateProfileAction = async (profileData) => {
    try {
      const response = await updateProfile(profileData)
      if (response.code === 200) {
        // 更新本地用户信息
        userInfo.value = { ...userInfo.value, ...response.data }
      }
      return response
    } catch (error) {
      throw error
    }
  }

  // 更新头像
  const updateAvatarAction = async (avatarUrl) => {
    try {
      // 直接更新本地用户信息，不调用API（因为API已经在profile页面调用过了）
      userInfo.value = { ...userInfo.value, avatar_url: avatarUrl }
      
      // 强制触发响应式更新
      await nextTick()
      
      console.log('头像更新完成，当前用户信息:', userInfo.value)
      return { code: 200, message: '头像更新成功' }
    } catch (error) {
      console.error('头像更新失败:', error)
      throw error
    }
  }

  return {
    // 状态
    token,
    userInfo,
    roles,
    permissions,
    
    // 计算属性
    isLoggedIn,
    hasRole,
    hasPermission,
    
    // 方法
    loginAction,
    logoutAction,
    getUserInfoAction,
    initUserInfo,
    resetUserInfo,
    getProfileAction,
    updateProfileAction,
    updateAvatarAction
  }
})
